<template>
  <el-dialog title="模板测试" :visible.sync="dialogVisible" width="70%" @close="handleDialogClose">
    <el-form :model="testForm" label-width="100px">
      <el-form-item label="测试日志">
        <el-input
          v-model="testForm.logText"
          type="textarea"
          :rows="6"
          placeholder="输入要测试的日志内容"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="onRunTest" type="primary">开始测试</el-button>
      </el-form-item>
      <el-form-item v-if="testForm.result" label="测试结果">
        <el-card>
          <div v-for="(result, index) in testForm.result" :key="index">
            <h4>{{ result.type }}</h4>
            <p><strong>匹配:</strong> {{ result.matched ? "是" : "否" }}</p>
            <p v-if="result.matched"><strong>提取字段:</strong></p>
            <el-table
              v-if="result.matched"
              :data="result.fields"
              border
              size="mini"
            >
              <el-table-column prop="name" label="字段名" width="120" />
              <el-table-column prop="value" label="值" />
            </el-table>
          </div>
        </el-card>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="handleCancel">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "TemplateTestDialog",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    template: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      testForm: {
        logText: "",
        result: null,
      },
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible;
      },
      set(val) {
        this.$emit("update:visible", val);
      },
    },
  },
  watch: {
    visible(newVal) {
      if (!newVal) {
        this.resetForm();
      }
    },
  },
  methods: {
    async onRunTest() {
      if (!this.testForm.logText.trim()) {
        this.$message.warning("请输入测试日志");
        return;
      }

      try {
        const response = await this.$axios.post(
          "http://localhost:8080/api/template/test",
          {
            templateId: this.template && this.template.id,
            logText: this.testForm.logText,
          }
        );

        if (response.data.success) {
          this.testForm.result = response.data.data;
          this.$message.success("测试完成");
        } else {
          this.$message.error(response.data.message || "测试失败");
        }
      } catch (error) {
        this.$message.error("测试失败: " + (error.message || "未知错误"));
      }
    },
    handleDialogClose() {
      this.resetForm();
    },
    resetForm() {
      this.testForm = {
        logText: "",
        result: null,
      };
    },
    handleCancel() {
      this.resetForm();
      this.$emit("close");
      this.$emit("update:visible", false);
    },
  },
};
</script> 